package leetcode.trie;

import java.util.HashMap;
import java.util.Map;

/**
 * leetCode 208
 *  Implement Trie (Prefix Tree)
 * 实现字典树
 * 翻译：从有序数组中去除重复项

 */
public class Trie208 {

    private TrieNode root;
    class TrieNode {
        boolean isLeaf;
        Map<Character,TrieNode> content;
        public TrieNode() {
            content = new HashMap<Character,TrieNode>();
        }
    }

    /** Initialize your data structure here. */
    public Trie208() {
        this.root = new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        if(word == null || word.length() == 0){
            return;
        }
        TrieNode node = root;
        TrieNode temp;
        for(int i = 0;i < word.length();i++){
            Character c = word.charAt(i);
            temp = node.content.get(c);
            if(temp == null){
                temp = new TrieNode();
                node.content.put(c, temp);
            }
            node = temp;
        }
        node.isLeaf = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        if(word == null || word.length() == 0){
            return false;
        }
        TrieNode node = root;
        TrieNode temp;
        for(int i = 0;i < word.length();i++){
            Character c = word.charAt(i);
            temp = node.content.get(c);
            if(temp == null){
                return false;
            }
            node = temp;
        }
        return node.isLeaf;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        if(prefix == null || prefix.length() == 0){
            return false;
        }
        TrieNode node = root;
        TrieNode temp;
        for(int i = 0;i < prefix.length();i++){
            Character c = prefix.charAt(i);
            temp = node.content.get(c);
            if(temp == null){
                return false;
            }
            node = temp;
        }
        return true;
    }
}
